package org.geektimes.rest.demo;

import org.apache.commons.io.IOUtils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

public class HttpURLConnectionDemo {

    public static void main(String[] args) throws Throwable {
        postConnection();
    }

    public static void getConnection() throws Exception {
        URI uri = new URI("http://127.0.0.1:8080/hello/world");
        URL url = uri.toURL();
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        try (InputStream inputStream = connection.getInputStream()) {
            System.out.println(IOUtils.toString(inputStream, "UTF-8"));
        }
        // 关闭连接
        connection.disconnect();
    }

    public static void postConnection() throws Exception {
        URL url = new URL("http://127.0.0.1:8080/register");
        // 打开和URL之间的连接
        HttpURLConnection con = (HttpURLConnection)url.openConnection();
        con.setRequestMethod("POST");//请求post方式
        con.setUseCaches(false);// Post请求不能使用缓存
        con.setDoInput(true);// 设置是否从HttpURLConnection输入，默认值为 true
        con.setDoOutput(true);// 设置是否使用HttpURLConnection进行输出，默认值为 false

        //设置header内的参数 connection.setRequestProperty("健, "值");
        con.setRequestProperty("Content-Type", "application/json");

        //设置body内的参数，put到JSONObject中
        String body="{\"username\": \"123\",\"password\": \"dddd\"}";

        // 建立实际的连接
        con.connect();

        con.getOutputStream().write(body.getBytes());

        // 获取服务端响应，通过输入流来读取URL的响应
        InputStream is = con.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        StringBuffer sbf = new StringBuffer();
        String strRead = null;
        while ((strRead = reader.readLine()) != null) {
            sbf.append(strRead);
            sbf.append("\r\n");
        }
        reader.close();

        // 关闭连接
        con.disconnect();

        // 打印读到的响应结果
        System.out.println("运行结束："+sbf.toString());

    }
}

